package com.zhou.utils.token;



import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description : jwtToken生成器
 * @Author : zyy
 * @Date: 2024/6/14  15:25
 */
public class JWTUtils {
    /**
     * 过期时间
     */
    private static final long EXPIRE = 1000 * 60 * 60 * 24;

    /**
     * jwt密匙
     */
    private static final String SECRET = "jwt_secret";

    public static String sign(String userCode, Map<String,Object> info) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            String token = JWT.create()
                    //将userCode保存到token里面
                    .withAudience(userCode)
                    //存放自定义数据
                    .withClaim("info",info)
                    //token过期时间
                    .withExpiresAt(date)
                    //token的密匙
                    .sign(algorithm);
            return token;
        }catch (Exception e) {

            throw new RuntimeException(e.getMessage());
        }
    }
    /**
     * 根据token获取userCode
     */
    public static String getUserCode(String token) {
        try {
            String userCode = JWT.decode(token).getAudience().get(0);
            return userCode;
        }catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 根据token获取自定义数据info
     */
    public static Map<String,Object> getInfo(String token) {
        try {
            Map<String,Object> info = JWT.decode(token).getClaim("info").asMap();
            return info;
        }catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 校验token
     */
    public static boolean checkSign(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    //.withClaim("username, username)
                    .build();
            verifier.verify(token);
            return true;
        }catch (JWTVerificationException e) {
            throw new RuntimeException("token无效，请重新获取");
        }
    }

    /**
     * 测试token校验登录
     */
//    public static void main(String[] args) {
//        Map<String,Object> info = new HashMap<>();
//        info.put("userCode","admin");
//        info.put("password","123456");
//        String admin = sign("admin", info);
//        System.out.println(admin);
//        System.out.println(getUserCode(admin));
//        System.out.println(checkSign(admin));
//        System.out.println(getInfo(admin));
//    }
}
